package concreteComponents;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import channel.Channel;

public class IntercambiadorConcreto {

	public Set<Channel<Serializable>> channelsS;
	public Set<Channel<Serializable>> channelsR;
	public Set<Integer> idCanalesS;
	
	public class AccionIntercambiarThread extends Thread{
		
		Channel<Serializable> channel;
		
		public AccionIntercambiarThread(Channel<Serializable> channel0) {
			this.channel = channel0;
		}
		
		@Override
		public void run() {
			while(true){
				String[] argumento = channel.receive().toString().split(" ");
				int channel = Integer.parseInt(argumento[0]);
				int mensaje = Integer.parseInt(argumento[1]);
				intercambiar(channel, mensaje);
			}
		}
	}
	
	public static void main(String[] args) throws InstantiationException,IllegalAccessException {
		
		IntercambiadorConcreto instance = new IntercambiadorConcreto();
		
		instance.channelsS = new HashSet<Channel<Serializable>>();
		instance.channelsR = new HashSet<Channel<Serializable>>();
		instance.idCanalesS = new HashSet<Integer>();
		
		String flag = "";
		for (int n = 1; n < args.length; n++) {
		
			if (args[n].equals("-cs")) {
				flag = "cs";
				continue;
			}
			
			if (args[n].equals("-cr")) {
				flag = "cr";
				continue;
			}
			
			if (flag.equals("cs")) {
				int i = Integer.parseInt(args[n]);
				Channel<Serializable> canal = new Channel<Serializable>(i);
				instance.channelsS.add(canal);
				instance.idCanalesS.add(canal.getChannelNumber());
			} 
			else {
				int i = Integer.parseInt(args[n]);
				instance.channelsR.add(new Channel<Serializable>(i));
			}
		}
		
		for (Channel<Serializable> channel : instance.channelsR){
			instance.new AccionIntercambiarThread(channel).start();
		}
	}

	public void intercambiar(int channel, int mensaje) {
		if(idCanalesS.contains(channel)){
			buscarCanal(channel).send(mensaje);
		}
	}

	public Channel<Serializable> buscarCanal(int idChannel) {
		Channel<Serializable> channel = null;
		for(Channel<Serializable> channel0 : channelsS ){
			if(idChannel == channel0.getChannelNumber()){
				channel = channel0;
			}
		}
		return channel;
	}
}
